package com.fin.zw.intelligentbot.controller;


import com.alibaba.fastjson.JSONObject;
import com.fin.zw.intelligentbot.annotation.CurrentUser;
import com.fin.zw.intelligentbot.entity.DialTask;
import com.fin.zw.intelligentbot.entity.TaskCustomer;
import com.fin.zw.intelligentbot.entity.UploadFile;
import com.fin.zw.intelligentbot.enums.TaskStatus;
import com.fin.zw.intelligentbot.job.TaskServiceJob;
import com.fin.zw.intelligentbot.model.ResulteWraper;
import com.fin.zw.intelligentbot.model.base.Customer;
import com.fin.zw.intelligentbot.model.base.PushTask;
import com.fin.zw.intelligentbot.model.request.DialTaskParamRequest;
import com.fin.zw.intelligentbot.model.request.DialTaskRequest;
import com.fin.zw.intelligentbot.model.request.RequestId;
import com.fin.zw.intelligentbot.model.request.TaskRecycleRequest;
import com.fin.zw.intelligentbot.model.response.DialTaskResponse;
import com.fin.zw.intelligentbot.model.session.SessionModel;
import com.fin.zw.intelligentbot.service.DialTaskService;
import com.fin.zw.intelligentbot.service.SocketService;
import com.fin.zw.intelligentbot.util.HeaderUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/task")
@Api(value = "任务管理", description = "任务管理")
public class DialTaskController {

    @Autowired
    private DialTaskService dialTaskService;

    @Autowired
    private SocketService socketService;

    @Autowired
    TaskServiceJob taskServiceJob;

    @GetMapping("/fetchPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", dataType = "int", paramType = "query",value = "页数 (0..N)"),
            @ApiImplicitParam(name = "size", dataType = "int", paramType = "query",value = "每页大小."),
            @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query",
                    value = "依据什么排序: 属性名(,asc|desc). ")})
    public ResponseEntity<Page<DialTaskResponse>> fetchPage(Pageable pageable,
                                                            DialTaskParamRequest request,
                                                            @ApiIgnore @CurrentUser SessionModel sessionModel) throws Exception {
        Page<DialTaskResponse> page = dialTaskService.queryDialTaskAll(pageable,request,sessionModel);
        return ResponseEntity.ok().body(page);
    }


    @GetMapping("/fetchTask")
    @ApiOperation(value = "查询任务",notes = "查询任务")
    public ResponseEntity<List<DialTaskResponse>> fetchTask(DialTaskParamRequest condition, @ApiIgnore @CurrentUser SessionModel sessionModel) throws Exception
    {
        List<DialTaskResponse> tasks = dialTaskService.fetchApi(condition, sessionModel);
        return ResponseEntity.ok().body(tasks);
    }

    @GetMapping("/fetch")
    @ApiOperation(value = "查询任务", notes = "查询任务")
    public ResponseEntity<List<DialTaskResponse>> fetch(DialTaskParamRequest condition, @ApiIgnore @CurrentUser SessionModel sessionModel) {
        // ResulteWraper wraper = new ResulteWraper();
        List<DialTaskResponse> tasks = new ArrayList<>();
        Map<DialTask, List<TaskCustomer>> taskGroup = dialTaskService.fetch(condition, sessionModel);
        taskGroup.forEach((tg, tcs) -> {
            DialTaskResponse dtr = new DialTaskResponse();
            BeanUtils.copyProperties(tg, dtr);
            dtr.setCustomers(tcs);
            tasks.add(dtr);
        });
        //wraper.setData(tasks);
        return ResponseEntity.ok().body(tasks);
    }


    @GetMapping("/fetchSimplifyTask")
    @ApiOperation(value = "查询任务", notes = "查询任务")
    public ResponseEntity<List<PushTask>> fetchSimplifyTask(DialTaskParamRequest condition, @ApiIgnore @CurrentUser SessionModel sessionModel) {
        List<PushTask> tasks = dialTaskService.fetchSimplifyTask(condition, sessionModel);
        return ResponseEntity.ok().body(tasks);
    }

    @PostMapping("/add")
    @ApiOperation(value = "创建任务信息",notes = "创建任务信息")
    public ResponseEntity<DialTaskResponse> add(@RequestBody DialTaskRequest request,
                                                @ApiIgnore @CurrentUser SessionModel sessionModel) throws Exception{
        ResulteWraper wraper = new ResulteWraper();
        DialTask task = dialTaskService.createDialTask(request, sessionModel, wraper);

        DialTaskResponse dtr = new DialTaskResponse();
        BeanUtils.copyProperties(task, dtr, "customers", "robots", "scene");

        return ResponseEntity.ok().body(dtr);
    }

    @RequestMapping(value = "/update",method = {RequestMethod.PUT,RequestMethod.PATCH})
    @ApiOperation(value = "更新任务信息",notes = "更新任务信息")
    public ResponseEntity<String> update(@RequestBody DialTaskRequest request,
                                                 @ApiIgnore @CurrentUser SessionModel sessionModel) throws Exception {
        dialTaskService.updateDialTask(request,sessionModel);
        return ResponseEntity.ok().body("操作成功");
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "任务信息删除",notes = "任务信息删除")
    public ResponseEntity<String> delete(@PathVariable String id,
                                                 @ApiIgnore @CurrentUser SessionModel sessionModel){
        dialTaskService.deleteDialTaskById(id,sessionModel);
        return ResponseEntity.ok().body("操作成功");
    }

    @PostMapping("/execute")
    @ApiOperation(value = "任务呼叫",notes = "任务呼叫")
    @Transactional
    public ResponseEntity<String> execute(@RequestBody DialTaskRequest request,
                                          @ApiIgnore @CurrentUser SessionModel sessionModel)  throws Exception {
        request.setStatus(TaskStatus.READY.toString());
        this.dialTaskService.updateDialTask(request,sessionModel);
        socketService.sendTaskInfoById(request.getId());
        return ResponseEntity.ok().body("操作成功");
    }


    @PostMapping("/cancle")
    @ApiOperation(value = "任务取消",notes = "任务取消")
    public ResponseEntity<String> cancle(@RequestBody DialTaskRequest request){
        socketService.cancelTask(request.getId());
        return ResponseEntity.ok().body("操作成功");
    }



    @PostMapping("/parse")
    @ApiOperation(value = "解析文件数据",notes = "解析文件数据")
    public ResponseEntity<JSONObject> prseCustomer(@RequestBody UploadFile ufile, @ApiIgnore @CurrentUser SessionModel sessionModel) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(String.format("{'columns':%s,'data':%s}",
                    this.dialTaskService.parseCSV(ufile)));
            return ResponseEntity.ok().body(jsonObject);
        } catch (Exception e) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("parse", "", "解析文件数据失败")).body(null);
        }
    }

    @GetMapping("/download")
    @ApiOperation(value = "下载导入数据模板", notes = "下载导入数据模板")
    public ResponseEntity<Void> download(HttpServletResponse response, @RequestParam("sceId") String sceId) throws Exception {
        dialTaskService.download(response, sceId);
        return ResponseEntity.ok().build();
    }


    @PostMapping("/taskRecycle")
    @ApiOperation(value = "任务回收", notes = "任务回收")
    public ResponseEntity<Void> taskRecycle(@RequestBody TaskRecycleRequest request,
                                            @ApiIgnore @CurrentUser SessionModel sessionModel) {
        dialTaskService.taskRecycle(request);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/pushTask")
    @ApiOperation(value = "任务的推送", notes = "任务的推送")
    public ResponseEntity<Void> pushTaskInfo(@RequestBody RequestId request) {
        socketService.sendTaskInfo(request.getId());
        return ResponseEntity.ok().build();
    }

    @PostMapping("/pushTaskById")
    @ApiOperation(value = "任务的推送", notes = "任务的推送")
    public ResponseEntity<Void> pushTaskById(@RequestBody RequestId request) {
        socketService.sendTaskInfoById(request.getId());
        return ResponseEntity.ok().build();
    }

    @GetMapping("/fetchCustomerByTaskId")
    @ApiOperation(value = "根据任务id获取客户信息", notes = "根据任务id获取客户信息")
    public ResponseEntity<List<Customer>> fetchCustomerByTaskId(@RequestParam("taskId") String taskId) {
        List<Customer> customers = dialTaskService.fetchCustomerByTaskId(taskId);
        return ResponseEntity.ok().body(customers);
    }


    @GetMapping("/testId")
    @ApiOperation(value = "任务的推送", notes = "任务的推送")
    public ResponseEntity<Void> testId(@RequestParam("taskId") String taskId) throws Exception{
        taskServiceJob.start(taskId);
        return ResponseEntity.ok().build();
    }
}
